package com.sbs.demo.filter;

import com.sbs.demo.common.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

@Order(Ordered.HIGHEST_PRECEDENCE + 1)
@Slf4j
@Component
public class TraceFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        long startTime = System.currentTimeMillis();
        servletRequest.setAttribute(CommonConstant.REQUEST_START_TIME_HEADER, startTime);
        HttpServletRequest request = ((HttpServletRequest) servletRequest);
        String uuid = UUID.randomUUID().toString();
        String clientIp = request.getHeader(CommonConstant.CLIENT_IP_HEADER);
        MDC.put(CommonConstant.TRACE_ID_HEADER, uuid);
        MDC.put(CommonConstant.CLIENT_IP_HEADER, clientIp);
        filterChain.doFilter(servletRequest, servletResponse);
        long spendTime = System.currentTimeMillis() - (Long) servletRequest.getAttribute(CommonConstant.REQUEST_START_TIME_HEADER);
        log.info("{} 花费时间: {}", request.getRequestURI(), spendTime + "ms");
    }
}
